<template>
  <div class="editor-body">
    <Toolbar
      class="editor-body-border"
      id="toolbar"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="styles"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onFocus="handleFocus"
      @onBlur="handleBlur"
      @onChange="handleChange"
      id="editor"
    />
    <mateSelectModal
      ref="mateSelectModalRef"
      @change="selectChange"
      :count="-1"
    ></mateSelectModal>
  </div>
</template>
<script lang="ts" name="editor" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  getCurrentInstance,
  computed,
  StyleValue,
} from "vue";
import { IDomEditor, Boot } from "@wangeditor/editor";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import mateSelectModal from "@/components/mate/select-modal/index.vue";

const props = withDefaults(
  defineProps<{
    height?: string;
    modelValue?: string;
    disabled?: boolean;
  }>(),
  {
    height: "500px",
    modelValue: "",
    disabled: false,
  }
);

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["update:modelValue"]);

const styles = computed<StyleValue>(() => {
  return [`height: ${props.height}`];
});

const mode = ref<any>();

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p></p>");

const mateSelectModalRef = ref<HTMLElement>();

const setFocus = () => {
  editorRef.value.focus();
};

const toolbarConfig = {
  toolbarKeys: [
    "headerSelect",
    "fontSize",
    "fontFamily",
    "lineHeight",
    "bold",
    "underline",
    "italic",
    "color",
    "bgColor",
    {
      key: "group-more-style",
      title: "更多",
      menuKeys: [
        "through",
        "blockquote",
        "code",
        "sup",
        "sub",
        "divider",
        "clearStyle",
      ],
    },
    "|",
    "bulletedList",
    "numberedList",
    {
      key: "group-justify",
      title: "对齐",
      menuKeys: [
        "justifyLeft",
        "justifyRight",
        "justifyCenter",
        "justifyJustify",
      ],
    },
    {
      key: "group-indent",
      title: "缩进",
      menuKeys: ["indent", "delIndent"],
    },
    "|",
    "emotion",
    "insertTable",
    "|",
    "undo",
    "redo",
  ],
  insertKeys: {
    index: 18,
    keys: ["imageTool"],
  },
};

// 初始化 MENU_CONF 属性

const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    imageTool: {
      callback() {
        proxy?.$refs["mateSelectModalRef"]?.open([]);
      },
    },
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  if (props.disabled) {
    editor.disable();
  } else {
    editor.enable();
  }
});

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor;
};
const handleFocus = (editor: IDomEditor) => {
  // console.log("focus", editor);
};
const handleBlur = (editor: IDomEditor) => {
  // console.log("blur", editor);
};
const handleChange = (editor: IDomEditor) => {
  emit("update:modelValue", editor.getHtml());
  // console.log("change:", editor.getHtml());
};

const selectChange = (data: string | string[]) => {
  const editor = editorRef.value;
  if (editor == null) {
    alert("kong");
    return;
  }

  if (typeof data == "object") {
    data.forEach((item: string) => {
      editor.dangerouslyInsertHtml(
        `<img style='width:100%;display: block;' src='${item}' />`
      );
    });
  } else {
    editor.dangerouslyInsertHtml(
      `<img style='width:100%;display: block;' src='${data}' />`
    );
  }
  editor.focus(true);
};

const setContent = (content:string) => {
  editorRef.value.setHtml(content)
}

onMounted(() => {
  setTimeout(() => {
    setFocus();
  }, 1000);
});

defineExpose({ setFocus ,setContent});
</script>    
<style scoped>
.editor-body {
  border: 1px solid var(--el-border-color);
  border-radius: var(--base-radius);
}
.editor-body-border {
  border-bottom: 1px solid var(--el-border-color);
}
</style>